package net.sudot.chess.task;

import net.sudot.chess.business.model.Room;
import net.sudot.chess.business.model.WechatGroup;
import net.sudot.chess.business.service.RoomService;
import net.sudot.chess.business.service.WechatGroupService;
import net.sudot.chess.util.WBihuizhiUtils;
import net.sudot.commons.lock.Lock;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 微信群回收处理
 *
 * @author tangjialin on 2018-11-12.
 */
@Component
public class WechatGroupRecycleTask {

    @Resource
    private RoomService roomService;
    @Resource
    private WechatGroupService wechatGroupService;

    /**
     * 微信群回收处理
     */
    @Lock(name = "lock:scheduled:wechatgroup:recycle:processing")
//    @Scheduled(cron = "${scheduled.wechatgroup.recycle.processing.cron}")
    public void recycleProcessing() {
        List<WechatGroup> wechatGroups = wechatGroupService.findAllUseList();
        if (wechatGroups == null || wechatGroups.isEmpty()) { return; }
        Map<Long, WechatGroup> wechatGroupMap = new HashMap<>(wechatGroups.size());
        for (WechatGroup wechatGroup : wechatGroups) {
            wechatGroupMap.put(wechatGroup.getId(), wechatGroup);
        }
        List<Room> roomList = roomService.findAllListAtPlaying();
        roomList.parallelStream().forEach(room -> {
            // 获取房间状态
            WBihuizhiUtils.RoomStatus status = WBihuizhiUtils.getRoomStatus(WBihuizhiUtils.getHtml(room.getUrl()));
            // 如果房间不是等待中,即可回收微信群
            if (status == null || status == WBihuizhiUtils.RoomStatus.WAIT) { return;}
            // 回收微信群
            Optional.ofNullable(wechatGroupMap.get(room.getWechatGroupId())).ifPresent(wechatGroup -> wechatGroupService.update(wechatGroup.setUsed(false)));
        });
    }

}
